<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Model\Address;
use App\Http\Model\Orders;
use App\Http\Model\OrdersInfo;
use App\Http\Model\User;
use App\Http\Model\Sign;
use App\Http\Model\Record;
use App\Http\Model\History;
use App\Http\Model\Help;
use App\Http\Model\IntegralOrders;
use App\Http\Model\Fenxiao;
use App\Http\Model\Withdrawals;
use DB;

class UserController extends Controller{

	// 个人中心
	public function my(){
		$orders = new Orders;
		$ordersInfo = Array();
		$ordersInfo[0] = $orders->where("status", 1)->where("user_id", session("uid"))->count();
		$ordersInfo[1] = $orders->where("status", 2)->where("user_id", session("uid"))->count();
		$ordersInfo[2] = $orders->where("status", 3)->where("user_id", session("uid"))->count();
		$ordersInfo[3] = $orders->where("status", 4)->where("user_id", session("uid"))->count();
        $fenxiao = new Fenxiao;
		//查询签到数据
		$user = New User;
        $sign = New Sign;
        $userId = session('uid');
        $fenxiaoInfo = $fenxiao->select('min_money')->first();
        $userData = $user->where('id',$userId)->first();
        $userData['count'] = $sign->where('user_id',$userId)->count();
		return view("home.user.my", ["ordersInfo" => $ordersInfo,'userData'=>$userData,'fenxiaoInfo'=>$fenxiaoInfo]);
	}

	// 收藏中心
	public function collection(){
		return view("home.user.collection");
	}

	// 选择收货地址
    public function address(Request $request){
        // dd(session("uid"));
    	$address = new Address;
    	$addressInfo = $address->where("user_id", session("uid"))->get();
    	return view("home.user.address", ["addressInfo" => $addressInfo]);
    }

	// 地址添加
	public function addAddress(){
		return view("home.user.add-address");
	}
    public function upAddress($id){
        $address = new Address;
        $addressInfo = $address->where('id',$id)->first();
        return view('home.user.update-address',[
            "addressInfo" => $addressInfo
        ]);
    }
    public function upAddressRes(Request $request){
        $address = new Address;
        $addressInfo = $address->find($request->input('id'));
        $addressInfo->name = $request->input('name');
        $addressInfo->tel = $request->input('tel');
        $addressInfo->sex = $request->input('sex');
        $addressInfo->birthday = $request->input('birthday');
        $addressInfo->youbian = $request->input('youbian');
        $addressInfo->detail = $request->input('detail');
        $addressInfo->type = $request->input('type')!='' ? 1:0;
        if($addressInfo->type==1){
            $address->where('user_id',session('uid'))->where('type',1)->update(['type'=>0]);
        }
        $addressInfo->save();
        return redirect('/address');
    }
    public function delAddress(Request $request){
        $address = new Address;
        $address->where('id',$request->input('id'))->delete();
        echo 1;
    }

	// 地址保存
	public function saveAddress(Request $request){
		$data = $request->all();
		$address = new Address;
		$address->user_id = session("uid");
        $lastAddress = $address->where('user_id',session('uid'))->first();
        if(count($lastAddress)<=0){
            $data['type'] = 1;
        }
		$address->name = $data["name"];
		$address->sex = $data["sex"];
		$address->tel = $data["tel"];
		$address->birthday = $data["birthday"];
		$address->youbian = $data["youbian"];
		$address->address = $data["address"];
		$address->detail = $data["detail"];
		$address->type = isset($data["type"]) && !empty($data["type"]) ? 1 : 0;
		$addressInfo = $address->where("user_id", session("uid"))->where("type", "1")->first();
		if($addressInfo && $address->type == 1){
			$address->where("user_id", session("uid"))->where("type", "1")->update(["type"=>0]);
		}
		$address->save();
        if($data["back"] == 1){
            return redirect('/address#back-1');
        }else if($data["back"] == 0){
		    return redirect('/address#back-0');
        }else{
            return redirect('/address');
        }
	}

	// 分销记录
	public function record(){
		$record = new Record;
        $fenxiao = new Fenxiao;
        $user = new User;
        $money = array();
        $num = 0;
        $grade = '';
        $nextMoney = '';
        $fenxiaoInfo = $fenxiao->first();
        $money[0] = $fenxiaoInfo->money_1;
        $money[1] = $fenxiaoInfo->money_2;
        $money[2] = $fenxiaoInfo->money_3;
        $money[3] = $fenxiaoInfo->money_4;
        $money[4] = $fenxiaoInfo->money_5;
        $moneys = $user->find(session('uid'))->money;
        $recordInfo = $record->select('record.*','user.money')->leftJoin('user','user.id','=','user_id')->where('user_id',session('uid'))->where('identity','1')->whereNotNull('recount')->orderBy('record.updated_at','desc')->get();
        //查询当前分销商信息
        $rebackMoneyTemp = $this->saleVolume(session('uid'),'1');

        if(is_array($rebackMoneyTemp)){
            $monthMoney = $rebackMoneyTemp['member'] + $rebackMoneyTemp['business'];
        }else{
            $monthMoney = 0;
        }

        foreach ($money as $k1 => $v1) {
            if($monthMoney>$v1 && ($v1!='0' || $k1=='0')){
                $num++;
            }else{
                if($monthMoney < $v1){
                    $nextMoney = $v1;
                }else{
                    $nextMoney = 'max';
                }
                break;
            }
        }
        // dd($rebackMoney);
        return view("home.user.record", [
            "recordInfo"=>$recordInfo,
            'moneys'=>$moneys,
            'min_money'=>$fenxiaoInfo->min_info,
            'monthMoney'=>$monthMoney,
            'num'=>$num,
            'fenxiaoInfo'=>$fenxiaoInfo,
            'nextMoney' => $nextMoney
            ]);

	}

	// 我的团队
	public function team(){
        $user = new User;
        $userId = session('uid');
        $userInfo = array();
        $userInfo = $user->where('pid',$userId)->get();
        // dd(session('uid'));
		return view("home.user.team",[
            "userInfo"=>$userInfo
        ]);
	}
	//用户签到
    public function addSign(Request $request){
        $sign = New Sign;
        $user = New User;
        $record = New Record;
        $userId = $request->input('id');
        $lastSign = $sign->where('user_id',$userId)->orderBy('created_at','desc')->first();
        if(!$lastSign || ((int)substr($lastSign->created_at,8,2)!=(int)date('d'))){
            $userData = $user->where('id',$userId)->first();
            $userData->integral = (int)$userData->integral+5;
            $sign->user_id = $userId;
            $record->num=0;
            $record->record=5;
            $record->user_id = $userId;
            $record->save();
			$sign->save();
            $userData->save();
            return 1;
        }else{
            return 0;
        }
    }

    // 成为分销商
    public function distributor(Request $request){
        // session(['uid'=>'22']);
        //微信关注Auth2.0授权
        // session(['uid'=>'22']);
        if($request->input('code') and empty(session('uid'))){
            $user = New User;
            $userInfo = $this->getUserInfo($request->input('code'));
            $userData = $user->where('open_id',$userInfo['openid'])->first();
            if($userData){
                session(['uid'=>$userData->id]);
            }else{
                $userArr=array();
                $userArr['open_id'] = $userInfo['openid'];
                $userArr['sex'] = $userInfo['sex'];
                $userArr['username'] = $userInfo['nickname'];
                $userArr['face'] = $userInfo['headimgurl'];
                $userArr['pid'] = session('pid');
                $id = DB::table('user')->insertGetId($userArr);
                session(['uid'=>$id]);
            }
        }
        return view("home.user.distributor");
    }

    public function saveDistributor(Request $request){
        $data = $request->all();
        // dd($data);
        $user = new User;
        $userInfo = $user->find(session("uid"));
        $userInfo->name = $data["name"];
        $userInfo->weixin = $data["weixin"];
        $userInfo->sfz = $data["sfz"];
        $userInfo->sfz_images = $data["url"];
        $userInfo->distributor_status = 1;
        if($userInfo->identity == 0){
        	$userInfo->pid = null;
        }
        $userInfo->save();
        return redirect("/");
    }

    // 申请成为分销商上传身份证图片
    public function distributorUploadImage(Request $request){
        $fileUrl = Array();
        $count = 0;
        $num = $request->input("num");
        if ($request->hasFile('file_all')) {
            foreach ($request->file('file_all') as $k => $v) {
                if ($v->isValid() && $count < $num) {
                    $destinationPath = "./upload/goods/distributor/";
                    $fileName = time().rand(100000,999999).'.'.$v->getClientOriginalExtension();
                    $v->move($destinationPath, $fileName);
                    array_push($fileUrl, "/upload/goods/distributor/".$fileName);
                    $count++;
                }
            }
        }
        echo json_encode($fileUrl);die;
    }
    //获取用户的消费总额
    public static function spendCount($userId){
        $orders = new Orders;
        $ordersInfo = new OrdersInfo;
        $ordersData = $orders->where('user_id',$userId)->where('status','>',3)->get();
        $sumPrice=0;
        if(count($ordersData)>0){
            foreach ($ordersData as $key => $value) {
                $ordersDetail = $ordersInfo->where('orders_id',$value->id)->get();
                foreach ($ordersDetail as $k => $v) {
                    $sumPrice += $v->price*$v->num;
                }
            }
        }
        return $sumPrice;
    }
    //历史记录
    public function history(){
        $history = new History;
        $historyInfo = $history->where('user_id',session('uid'))->orderBy('updated_at','desc')->get();
        return view('home.user.history',["historyInfo"=>$historyInfo]);
    }
    //帮助中心
    public function helpList(){
        $help = new Help;
        $helpInfo = $help->orderBy('updated_at','desc')->get();
        return view('home.user.help',[
            "helpInfo" => $helpInfo
        ]);
    }
    //帮助中心详情页
    public function helpDetail($id){
        $help = new Help;
        $helpDetail = $help->find($id);
        return view("home.user.helpDetail",[
            "helpDetail" => $helpDetail
        ]);
    }
    //兑换记录
    public function integralOrders(){
        $integralOrders = new IntegralOrders;
        $integralOrdersInfo = $integralOrders->where('user_id',session('uid'))->get();
        return view("home.user.integral-orders", ["integralOrdersInfo"=>$integralOrdersInfo]);
    }
    // 确认收货
    public function goodsIntegralReceipt(Request $request){
        $integralOrders = new IntegralOrders;
        $integralOrdersInfo = $integralOrders->find($request->input("id"));
        $integralOrdersInfo->status = 2;
        $integralOrdersInfo->save();
        echo 1;die;
    }
    // 快递查询
    public function integralOrdersLogistic($id){
        $integralOrders = new IntegralOrders;
        $integralOrdersInfo = $integralOrders->find($id);
        $num = $integralOrdersInfo->orders_num;
        // $num = '51010904478878935';
        $logistic_code = $integralOrdersInfo->logistic_code;
        // $logistic_code = '3976331681071';
        $logistic_company = Config::get('app.kdn_company_name');
        // $logistic_company = "YD";
        $logisticResult = json_decode($this->getOrderTracesByJson($num, $logistic_code, $logistic_company));
        return view("home.orders.logistic", ["logistic"=>$logisticResult, "ordersInfo"=>$integralOrdersInfo]);
    }

    /**
     * Json方式 查询订单物流轨迹
     */
    public function getOrderTracesByJson($num, $logistic_code, $logistic_company){
        $requestData = "{'OrderCode':'$num','ShipperCode':'$logistic_company','LogisticCode':'$logistic_code'}";

        $datas = array(
            'EBusinessID' => Config::get('app.kdn_user_id'),
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, Config::get('app.kdn_api_key'));
        $result = $this->sendPost('http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx', $datas);

        //根据公司业务处理返回的信息......

        return $result;
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    public function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    public function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }
    //提现申请
    public function withdrawals(Request $request){
        $withdrawals = new Withdrawals;
        $withdrawals->user_id = $request->input('user_id');
        $withdrawals->money = $request->input('money');
        $this->withdrawalsTemplate($request->input('user_id'));
        $res = $withdrawals->save();
        if($res){
            echo 1;
        }else{
            echo 0;
        }
    }
    //提现记录
    public function withdrawalsHistory(){
        $withdrawals = new Withdrawals;
        $fenxiao = new Fenxiao;
        $user = new User;
        $withdrawalsInfo = $withdrawals->where('user_id',session('uid'))->orderBy('created_at','desc')->get();
        $min_money = $fenxiao->first()->min_money;
        $money = $user->find(session('uid'))->money;
        return view('home.user.withdrawalsHistory',['withdrawalsInfo'=>$withdrawalsInfo,'money'=>$money,'min_money'=>$min_money]);
    }
}
